//
//  CZEmoticonKeyboard.swift
//  表情键盘新工程-74.准备
//
//  Created by itcast on 16/5/21.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

/// 表情键盘的view
class CZEmoticonKeyboard: UIView {
    
    weak var textView: UITextView?
    
    private let cellReuseIdentifier = "cellReuseIdentifier"
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        // 指定frame
        let newFrame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 216)
        super.init(frame: newFrame)
        
        prepareUI()
    }
    
    private func prepareUI() {
//        backgroundColor = UIColor.brownColor()
        self.addSubview(collectionView)
        self.addSubview(pageControl)
        self.addSubview(emotivonToolBar)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false 
        emotivonToolBar.translatesAutoresizingMaskIntoConstraints = false
        
        self.addConstraints(        NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : self.collectionView]))
       
        self.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : self.emotivonToolBar]))
        

        self.addConstraints(        NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : self.collectionView, "tb" : self.emotivonToolBar]))
        
        // pageControl
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 25))
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let itemSize = collectionView.frame.size
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = itemSize
    }
    
    private lazy var collectionView: UICollectionView = {
       let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        cv.registerClass(CZEmoticonPageCell.self, forCellWithReuseIdentifier: self.cellReuseIdentifier)
        cv.bounces = false
        cv.pagingEnabled = true
        cv.dataSource = self
        cv.delegate = self
        return cv
    }()
    
    private lazy var pageControl: UIPageControl = {
       let pageControl = UIPageControl()
//        pageControl.numberOfPages = 5
//        pageControl.currentPage = 2
//        pageControl.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
//        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        return pageControl
    }()
    
    private lazy var emotivonToolBar: CZEmoticonToolBar = {
        let toolBar = CZEmoticonToolBar()
        
        
        toolBar.delegate = self
        
        return toolBar
    }()
    
//     private var cellCounts = [1, 6, 4, 2]
}

extension CZEmoticonKeyboard: CZEmoticonToolBarDelegate {
    
    func didSelectButtonType(didSelectedType: CZEmoticonToolBarType) {
        
        let indexPath = NSIndexPath(forItem: 0, inSection: didSelectedType.rawValue)
        collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.Left)
        setupPageControl(indexPath)
    }
}

extension CZEmoticonKeyboard: UICollectionViewDataSource,UICollectionViewDelegate{
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return CZEmoticonManager.sharedManager.emoticonPackageModels.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let emoticonPackageModel = CZEmoticonManager.sharedManager.emoticonPackageModels[section]
        return emoticonPackageModel.pageEmotions.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellReuseIdentifier, forIndexPath: indexPath) as! CZEmoticonPageCell
        cell.backgroundColor = UIColor.whiteColor()
//        cell.backgroundColor = UIColor.lightGrayColor()
        cell.indexPath = indexPath
        let emoticonPackageModel = CZEmoticonManager.sharedManager.emoticonPackageModels[indexPath.section]
        let pageEmoticon = emoticonPackageModel.pageEmotions[indexPath.item]
        cell.pageEmoticon = pageEmoticon
        cell.delegate = self
        return cell
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        var refPoint = collectionView.center
        refPoint.x += collectionView.contentOffset.x
        for cell in collectionView.visibleCells(){
            if cell.frame.contains(refPoint){
                let indexPath = collectionView.indexPathForCell(cell)
                emotivonToolBar.switchSelectedButtonWitchSection(indexPath!.section)
                setupPageControl(indexPath!)
            }
        }
    }
    
    private func setupPageControl(indexPath: NSIndexPath){
        let emoticonPackageModel = CZEmoticonManager.sharedManager.emoticonPackageModels[indexPath.section]
        pageControl.numberOfPages = emoticonPackageModel.pageEmotions.count
        pageControl.currentPage = indexPath.item
        pageControl.hidden = (indexPath.section == 0)
    }
}

extension CZEmoticonKeyboard: CZEmoticonPageCellDelegate{
    func emoticonPageCellDidClickDeleteButton() {
         textView?.deleteBackward()
    }
    
    func emoticonPageCellDidClickEmoticonButton(emoticonModel: CZEmoticonModel){
        textView?.insertEmoticon(emoticonModel)
        CZEmoticonManager.sharedManager.addRecentEmoticon(emoticonModel)
    }
    
    
}
